import {ptUrl} from './env.js'

const httpTokenRequest = (url,method, data) => {
	let token = "Bearer ";
	token+= uni.getStorageSync('token');
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: ptUrl + url,
		data: data,
		method: method,
		header:{
			'Authorization': token
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				res = res[1]
				if(res.data.code == 0){
					resolve(res)
				}else if(res.data.code == 1){
					uni.removeStorageSync('token');
					uni.removeStorageSync('sessionId');
					uni.showToast({
						title: res.data.message,
						icon: "error",
						duration: 1500
					})
					setTimeout(function () {
						uni.navigateTo({
							url: '/pages/index/index'
						})
					}, 1500)
				}else if(res.data.code == 2){
					uni.showToast({
						title: res.data.message,
						icon: "error",
						duration: 2000
					})
				}		
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

export default httpTokenRequest
